const Answer = require('../models/answers')
class AnswerCtl {
    // 查询答案
    async find(ctx) {
        const { per_page = 10 } = ctx.query
        const page = Math.max(ctx.query.page * 1, 1) - 1 // 第几页
        const perPage = Math.max(per_page * 1, 1) // 每页有几条
        // skip 跳过前面的n条数据
        const q = new RegExp(ctx.query.q)
        ctx.body = await Answer
            .find({ content: q, questionId: ctx.params.questionId })
            .limit(perPage)
            .skip(page * perPage)
    }
    // 查询特定答案
    async findById(ctx) {
        const { fields = '' } = ctx.query
        const selectFields = fields.split(';').filter(f => f).map(f => '+' + f).join(' ')
        const answer = await Answer.findById(ctx.params.id).select(selectFields).populate('answerer')
        ctx.body = answer
    }
    // 新建答案
    async create(ctx) {
        ctx.verifyParams({
            content: { type: 'string', required: true },
        })
        const answerer = ctx.state.user._id
        const { questionId } = ctx.params
        const answer = await new Answer({ ...ctx.request.body, answerer, questionId }).save()
        ctx.body = answer
    }
    async update(ctx) {
        ctx.verifyParams({
            content: { type: 'string', required: false },
        })
        const answer = await Answer.findByIdAndUpdate(ctx.params.id, ctx.request.body)
        ctx.body = answer
    }
    // 检查答案是否存在
    async checkAnswerExist(ctx, next) {
        const answer = await Answer.findById(ctx.params.id).select('+answerer')
        if (!answer) { ctx.throw(404, '答案不存在') }
        // 只有在路由里面包含questionId，只有在删改查答案时候才检查此逻辑，赞、踩答案时候不检查
        if (ctx.params.questionId && answer.questionId !== ctx.params.questionId) {
            ctx.throw(404, '该问题下没有此答案')
        }
        // 与update共用findById
        ctx.state.answer = answer
        await next()
    }
    // 检查当前登录者是否是提出该答案的人
    async checkAnswerer(ctx, next) {
        const { answer } = ctx.state
        if (answer.answerer.toString() !== ctx.state.user._id) {
            ctx.throw(403, '没有权限')
        }
        await next()
    }
    async delete(ctx) {
        await Answer.findByIdAndRemove(ctx.params.id)
        ctx.status = 204
    }
}

module.exports = new AnswerCtl()
